<?php

namespace app\controller;

use app\BaseController;
use think\facade\App;
use think\Request;
use think\facade\Cache; // 引入 Cache 门面
use think\facade\Cookie; // 引入 Cookie 门面
use app\model\User; // 新增：引入用户模型
class Index extends BaseController
{
    public function index()
    {
        $openid = Cookie::get('openid');
        // 构造缓存键，例如 'wechat_openid_' 加上用户ID
        $cacheKey = 'wechat_userinfo1_' . $openid;
        // 从缓存中获取 openid
        $user = "";
        // 如果缓存中不存在 openid，则进行 OAuth 授权
        $wechat = App::make('wechat');
        if (!$user) {
            
            $oauth = $wechat->getOAuth();
            $redirectUrl = $oauth->scopes(['snsapi_userinfo'])->redirect();
            return redirect($redirectUrl);
        } else {
            return view('index/index', ['user' => $user]);
        }
    }
    public function login(Request $request)
    {
        $code = $request->param('code');
        if (empty($code)) {
            return json(['status' => 'error', 'message' => '授权码不能为空'], 400);
        }
        try {
            $wechat = App::make('wechat');
            $oauth = $wechat->getOAuth();
            $user = $oauth->userFromCode($code);
            if (!$user || empty($user->getId())) { // Assuming getId() returns the openid or a unique identifier
                return view('index/fail');
            }
            // 从 $user 对象获取用户信息
            $openid = $user->getId(); // OpenID
            $nickname = $user->getNickname(); // 昵称
            $avatar = $user->getAvatar(); // 头像地址
            $userInfo = $user->getRaw(); // 原始 API 返回的结果
            // 准备要存储的用户数据
            $sessionData = [
                'openid' => $openid,
                'nickname' => $nickname,
                'avatar' => $avatar,
                'original_data' => $userInfo // 可以选择性存储原始数据
            ];
            // 存储用户信息到 Session
            Cookie::set('openid', $openid);
            // 构造缓存键并缓存用户信息
            $cacheKey = 'wechat_userinfo1_' . $openid; // 使用更明确的缓存键
            Cache::set($cacheKey, $sessionData, $user->getExpiresIn() ?: 3600); // 使用微信返回的过期时间，若无则默认1小时
            // 新增：持久化到数据库
            $dbUser = User::where('openid', $openid)->find();
            if ($dbUser) {
                $dbUser->save([
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'original_data' => json_encode($userInfo, JSON_UNESCAPED_UNICODE)
                ]);
            } else {
                // echo 1;exit;
                User::create([
                    'openid' => $openid,
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'original_data' => json_encode($userInfo, JSON_UNESCAPED_UNICODE)
                ]);
            }
            return redirect((string)url('/')); // 重定向到首页或其他页面
        } catch (\Exception $e) {
            // echo $e->getMessage();exit;
            return view('index/fail');
        }
    }
    // 验证
    public function verify()
    {
        // 获取参数
        $signature = isset($_GET["signature"]) ? $_GET["signature"] : '';
        $timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : '';
        $nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : '';
        $echostr = isset($_GET["echostr"]) ? $_GET["echostr"] : '';

        // 获取 token
        $token = config('wechat.token');
        if (empty($token)) {
            die('Token is not configured correctly.');
        }

        // 拼接字符串
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        // 验证签名
        if ($tmpStr == $signature) {
            echo $echostr; // 返回 echostr
        } else {
            echo 'Invalid request'; // 返回错误信息
        }
    }
}
